#! /usr/bin/env python3

import time

import asyncio


def Timer(func):
    def inner(*args, **kwargs):
        start = time.time() 
        func(*args, **kwargs)
        end = time.time()
        print(f"{func} run time: {end-start:2.3f}")
    return inner


async def work(work_name):
    print(f"start {work_name} ...")
    await asyncio.sleep(2)
    print(f"finish {work_name} ...")


async def main_1():
    print("*" * 25)

    # 当任务被阻塞时，线程会切换到其它“任务”
    result_1 = await work('A')
    # await后接的是协程对象，而当前只有一个任务，所以会继续等待
    print("result_1 ", result_1)

    result_2 = await work('B')
    print('result_2', result_2)
    print("-" * 25)


async def main_2():
    print("*" * 25)
    # 创建两个任务
    t1 = asyncio.create_task(work('a'))
    t2 = asyncio.create_task(work('b'))
    # 当任务被阻塞时，线程切换到其它任务
    result_1 = await t1
    print("result_1 ", result_1)
    result_2 = await t2
    print("result_2", result_2)
    print("-" * 25)


async def main_3():
    print("*" * 25)
    tasks = [ asyncio.create_task(work(i), name=f'task_{i}') for i in 'AB' ]
    done, pending = await asyncio.wait(tasks, timeout=None)
    print(done, pending)
    print("-" * 25)


@Timer
def main():
    asyncio.run(main_1())
    print()
    asyncio.run(main_2())
    print()
    asyncio.run(main_3())


main()
